package com.ruoyi.framework.websocket;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * WebSocket 消息处理，支持通过UID传输设备数据
 *
 * @author 张沐
 */
@Component
@ServerEndpoint("/websocket/message/{uid}")
public class WebSocketServer
{
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    /**
     * 存储UID与Session的映射
     */
    private static final ConcurrentHashMap<String, Session> uidSessionMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法，接收前端传递的UID
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) throws Exception
    {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag)
        {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        }
        else
        {
            // 添加用户并存储UID与Session的映射
            WebSocketUsers.put(session.getId(), session);
            uidSessionMap.put(uid, session);
            LOGGER.info("\n 建立连接 - UID: {}, Session: {}", uid, session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
            WebSocketUsers.sendMessageToUserByText(session, "连接成功，UID: " + uid);
            // 发送设备数据
//            sendDeviceData(uid, session);
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session)
    {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
        String uid = getUidBySession(session);
        boolean removeFlag = WebSocketUsers.remove(session.getId());
        if (!removeFlag)
        {
            // 获取到信号量则需释放
            SemaphoreUtils.release(socketSemaphore);
        }
        // 移除UID映射
        if (uid != null)
        {
            uidSessionMap.remove(uid);
        }
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {
        if (session.isOpen())
        {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        String uid = getUidBySession(session);
        LOGGER.info("\n 连接异常 - UID: {}, Session: {}", uid, sessionId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移除用户
        WebSocketUsers.remove(sessionId);
        // 移除UID映射
        if (uid != null)
        {
            uidSessionMap.remove(uid);
        }
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * UUID获取 Session
     */
    public static Session getSessionByUid(String uid){
        return uidSessionMap.get(uid);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        String uid = getUidBySession(session);
        String msg = message.replace("你", "我").replace("吗", "");
        LOGGER.info("\n 收到消息 - UID: {}, 消息: {}", uid, message);
        WebSocketUsers.sendMessageToUserByText(session, msg);
        // 可根据消息内容触发设备数据发送
//        sendDeviceData(uid, session);
    }

    /**
     * 根据UID获取Session
     */
    private String getUidBySession(Session session)
    {
        return uidSessionMap.entrySet().stream()
                .filter(entry -> entry.getValue().equals(session))
                .map(ConcurrentHashMap.Entry::getKey)
                .findFirst()
                .orElse(null);
    }

    /**
     * 发送设备数据到指定Session
     */
    public void sendDeviceData(String uid, Session session, JSONObject data)
    {
        try
        {
            // 模拟获取设备数据（实际应从数据库或服务获取）
            String deviceData = getDeviceDataByUid(uid);
            WebSocketUsers.sendMessageToUserByText(session, deviceData);
            LOGGER.info("\n 发送设备数据 - UID: {}, 数据: {}", uid, deviceData);
        }
        catch (Exception e)
        {
            LOGGER.error("\n 发送设备数据失败 - UID: {}, 错误: {}", uid, e.getMessage());
            WebSocketUsers.sendMessageToUserByText(session, "获取设备数据失败");
        }
    }

    /**
     * 模拟根据UID获取设备数据（需根据实际业务逻辑实现）
     */
    private String getDeviceDataByUid(String uid)
    {
        // 这里是模拟数据，实际应从数据库或服务获取
        return "{\"uid\": \"" + uid + "\", \"device\": \"Device-" + uid + "\", \"status\": \"active\", \"data\": \"Sample data\"}";
    }

    /**
     * 向指定UID发送设备数据
     */
    public static void sendDeviceDataToUid(String uid, String data)
    {
        Session session = uidSessionMap.get(uid);
        if (session != null && session.isOpen())
        {
            WebSocketUsers.sendMessageToUserByText(session, data);
            LOGGER.info("\n 向UID {} 发送数据: {}", uid, data);
        }
        else
        {
            LOGGER.warn("\n UID {} 未找到或连接已关闭", uid);
        }
    }
}